package com.toman.ui.work.workshop;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.OperationorderAllMappingsDto;
import com.toman.JavaBean.SendworkorderEntity;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.CustomProgressBar;
import com.toman.widget.DragFloatActionButton;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class DispatchingInfActivity extends ToolBarActivity {
    SendworkorderEntity bean;
    String status;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.pb_base)
    CustomProgressBar pbBase;
    @BindView(R.id.tv_completed_count)
    TextView tvCompletedCount;
    @BindView(R.id.tv_demand_count)
    TextView tvDemandCount;
    @BindView(R.id.tv_qualified_count)
    TextView tvQualifiedCount;
    @BindView(R.id.tv_waste_count)
    TextView tvWasteCount;
    @BindView(R.id.tv_scrapped_count)
    TextView tvScrappedCount;
    @BindView(R.id.tv_remake_count)
    TextView tvRemakeCount;
    @BindView(R.id.tv_reuse_count)
    TextView tvReuseCount;
    @BindView(R.id.rl_progress)
    RelativeLayout rlProgress;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.rl_more)
    RelativeLayout rlMore;
    @BindView(R.id.tv_sendwork_code)
    TextView tvSendworkCode;
    @BindView(R.id.rl_order_code)
    RelativeLayout rlOrderCode;
    @BindView(R.id.tv_sendwork_date)
    TextView tvSendworkDate;
    @BindView(R.id.rl_order_num)
    RelativeLayout rlOrderNum;
    @BindView(R.id.tv_completework_date)
    TextView tvCompleteworkDate;
    @BindView(R.id.tv_plan_id)
    TextView tvPlanId;
    @BindView(R.id.tv_customer)
    TextView tvCustomer;
    @BindView(R.id.tv_artline)
    TextView tvArtline;
    @BindView(R.id.tv_product_name)
    TextView tvProductName;
    @BindView(R.id.et_batch_number)
    EditText etBatchNumber;
    @BindView(R.id.et_stove_number)
    EditText etStoveNumber;
    @BindView(R.id.et_sendwork_count)
    EditText etSendworkCount;
    @BindView(R.id.tv_check_man)
    TextView tvCheckMan;
    @BindView(R.id.rl_check)
    RelativeLayout rlCheck;
    @BindView(R.id.tv_check_time)
    TextView tvCheckTime;
    @BindView(R.id.rl_check_time)
    RelativeLayout rlCheckTime;
    @BindView(R.id.tv_edit_man)
    TextView tvEditMan;
    @BindView(R.id.tv_edit_time)
    TextView tvEditTime;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.ll_more)
    LinearLayout llMore;
    @BindView(R.id.ll_order)
    LinearLayout llOrder;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.rl_list)
    RelativeLayout rlList;
    CommonAdapter<OperationorderAllMappingsDto> adapter;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.fb_chilid)
    DragFloatActionButton fbChilid;
    @BindView(R.id.scroll)
    ScrollView scroll;
    @BindView(R.id.et_sendwork_count_title)
    TextView etSendworkCountTitle;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dispatching_inf);
        ButterKnife.bind(this);
        initToolBar(BaseEnum.DISPATCHING.name + "详情");
        initIntent();
        initView();
    }


    private void initIntent() {
        status = getIntent().getStringExtra("status");
        bean = (SendworkorderEntity) getIntent().getSerializableExtra("bean");
    }

    private void initView() {
        initAdapter();
        tvSendworkDate.setText(bean.getSendworkDate());
        tvCompleteworkDate.setText(bean.getCompleteworkDate());
        tvSendworkCode.setText(bean.getSendworkCode());
        tvPlanId.setText(bean.getPlanEntity().getPlanNum());
        tvCustomer.setText(bean.getPlanEntity().getCustomer());
        tvArtline.setText(bean.getOperationArtlineEntity().getArtlineName());
        tvProductName.setText(bean.getProductEntity().getProductName());
        etBatchNumber.setText(bean.getBatchNumber());
        etStoveNumber.setText(bean.getStoveNumber());
        etSendworkCount.setText(bean.getSendworkCount() + "");
        tvQualifiedCount.setText("合格数量:" + bean.getSendworkStaticsCount().getQualifiedCount() + "");
        tvScrappedCount.setText("报废数量:" + bean.getSendworkStaticsCount().getScrappedCount() + "");
        tvCompletedCount.setText(bean.getSendworkStaticsCount().getCompletedCount() + "");
        tvWasteCount.setText("料废数量:" + bean.getSendworkStaticsCount().getWasteCount() + "");
        tvRemakeCount.setText("返工数量:" + bean.getSendworkStaticsCount().getRemakeCount() + "");
        tvReuseCount.setText("回用数量:" + bean.getSendworkStaticsCount().getReuseCount() + "");
        tvDemandCount.setText(bean.getSendworkCount() + "");
        pbBase.setMaxProgress((Integer.parseInt(bean.getSendworkCount() + "")));
        if (bean.getSendworkCount() >= bean.getSendworkStaticsCount().getCompletedCount()) {
            pbBase.setCurProgress(Integer.parseInt(bean.getSendworkStaticsCount().getCompletedCount() + ""), 2000);
        } else {
            pbBase.setCurProgress(Integer.parseInt(bean.getSendworkCount() + ""), 2000);
        }
        tvEditMan.setText(bean.getUpdateUser().getRealName());
        tvEditTime.setText(bean.getUpdateTime());
        tvCheckMan.setText(bean.getAuditUser().getRealName());
        tvCheckTime.setText(bean.getAuditTime());
        ViewUtil.unedit(etBatchNumber, etSendworkCount, etStoveNumber);
        ViewUtil.unclick(tvCompleteworkDate, tvSendworkDate);
        if (status.equals("0")) {
            ViewUtil.gone(rlCheck, rlCheckTime);
        } else if (status.equals("3")) {
            ViewUtil.done(etBatchNumber, etSendworkCount, etStoveNumber, tvCompleteworkDate, tvSendworkDate);
        }

        ToastUtil.print("数量" + bean.getOperationorderAllMappings().size());
    }

    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        lv.setLayoutManager(manager);
        adapter = new CommonAdapter<OperationorderAllMappingsDto>(this, R.layout.item_item_list_dispatching, bean.getOperationorderAllMappings()) {
            @Override
            protected void convert(ViewHolder holder, OperationorderAllMappingsDto item, int position) {
                holder.setText(R.id.tv_name, item.getOrderName());
            }
        };
        lv.setAdapter(adapter);
        lv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));


        adapter.notifyDataSetChanged();
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", bean);
                bundle.putInt("position", position);
                bundle.putString("status", status);

                IntentUtils.startActivityForResult(DispatchingInfActivity.this, DispatchingChildChildInfActivity.class, 1000, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    public void add() {
        String[] item = new String[]{"派工数量"};//直接初始化
        if (ViewUtil.isNull(getApplicationContext(), item, etSendworkCount)) {
            return;
        }
        else {
            if (etSendworkCount.getText().toString().equals("0")){
                ToastUtil.error(this,"派工数量不得为0");
                return;
            }
        }


        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", bean.getId() + "");
        map.put("sendworkDate", tvSendworkDate.getText().toString());
        map.put("completeworkDate", tvCompleteworkDate.getText().toString());
        map.put("planId", bean.getPlanEntity().getId() + "");
        map.put("sendworkCount", etSendworkCount.getText().toString());
        map.put("artlineId", bean.getOperationArtlineEntity().getId() + "");
        map.put("stoveNumber", etStoveNumber.getText().toString());
        map.put("batchNumber", etBatchNumber.getText().toString());

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_sendworkorder_update)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", getClass().toString() + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_edit, menu);


        MenuItem menuItem = menu.findItem(R.id.menu_edit);
        if (status.equals("3")) {
            menuItem.setVisible(false);
        }
        if (!PermissonUtils.contains(this, BaseEnum.DISPATCHING.has(PermEnum.EDIT))) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_edit:
                        if (item.getTitle().equals("编辑")) {
                            item.setTitle("完成");
                            ViewUtil.edit(etBatchNumber, etSendworkCount, etStoveNumber);
                            ViewUtil.click(tvCompleteworkDate, tvSendworkDate);
ViewUtil.necessary(etSendworkCountTitle);

                        } else {
                            add();

                        }
                        break;
                }
                return false;
            }
        });

        return true;
    }

    @OnClick({R.id.tv_sendwork_date, R.id.tv_completework_date, R.id.rl_more, R.id.fb_chilid})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_sendwork_date:
                ViewUtil.getDate(this, tvSendworkDate);
                break;
            case R.id.tv_completework_date:
                ViewUtil.getDate(this, tvCompleteworkDate);
                break;
            case R.id.rl_more:
                ViewUtil.hide(llMore, ivMore);
                break;
            case R.id.fb_chilid:
                Bundle bundle = new Bundle();
                bundle.putString("status", status);
                bundle.putSerializable("bean", bean);
                IntentUtils.startActivityForResult(DispatchingInfActivity.this, DispatchingChildInfActivity.class, 1000, bundle);
                break;
        }
    }

    @OnClick(R.id.rl_list)
    public void onViewClicked() {
        Bundle bundle = new Bundle();
        bundle.putString("status", status);
        bundle.putSerializable("bean", bean);
        IntentUtils.startActivityForResult(DispatchingInfActivity.this, DispatchingChildInfActivity.class, 1000, bundle);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            bean = (SendworkorderEntity) data.getSerializableExtra("bean");
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}